<template>
  <Grid
    ref="gridRef"
    :fetch-data="fetchData"
    border
    header-align="center"
    align="center"
    height="95%"
    auto-resize
    seq-serial
    remote-sort
    :pager="pagerConfig"
    :edit-config="{ trigger: 'dblclick', mode: 'cell', showStatus: true }"
    @edit-closed="editClosed"
    :mouse-config="{ selected: true }"
    :keyboard-config="{ isArrow: true, isDel: true, isTab: true }"
    show-footer :footer-method="footerMethod"
  >
  <template #toolbar>
      <GridToolbar setting>
        <template #buttons>
          <div style="display: flex;">
            <Select v-model="idc2" placeholder="识别码2" clearable filterable allow-create is-drop-inherit-width>
              <Option v-for="item in idc2Op" :key="item" :label="item" :value="item"></Option>
            </Select>
            <Select v-model="supplied" placeholder="供应商" clearable filterable allow-create is-drop-inherit-width>
              <Option v-for="item in suppliedOp" :key="item" :label="item" :value="item"></Option>
            </Select>
            <Select v-model="material_category" placeholder="物料品类" clearable filterable allow-create is-drop-inherit-width>
              <Option v-for="item in materialCategoryOp" :key="item" :label="item" :value="item"></Option>
            </Select>
            <Select v-model="material_name" placeholder="物料名称" clearable filterable allow-create is-drop-inherit-width>
              <Option v-for="item in materialNameOp" :key="item" :label="item" :value="item"></Option>
            </Select>
          </div>
          <div style="display: flex; margin-top: 5px;">
              <Select v-model="color" placeholder="色号&颜色" clearable filterable allow-create is-drop-inherit-width>
                <Option v-for="item in colorOp" :key="item" :label="item" :value="item"></Option>
              </Select>
              <Select v-model="specification" placeholder="规格" clearable filterable allow-create is-drop-inherit-width>
                <Option v-for="item in specificationOp" :key="item" :label="item" :value="item"></Option>
              </Select>
              <Select v-model="work_order_num" placeholder="工单号" clearable filterable allow-create is-drop-inherit-width>
                <Option v-for="item in workOrderNumOp" :key="item" :label="item" :value="item"></Option>
              </Select>
            <Button type="primary" style="margin-left: 10px;" @click="handleSearch">查询</Button>
            <Button style="margin-left: 10px;" @click="exportFile">导出</Button>
          </div>
        </template>
      </GridToolbar>
    </template>
    <GridColumn type="index" width="60"  fixed="left"></GridColumn>
    <GridColumn field="supplied" title="供应商" min-width="120" show-icon></GridColumn>
    <GridColumn field="material_category" title="物料品类" min-width="120" show-icon></GridColumn>
    <GridColumn field="material_num" title="物料编号" min-width="120" show-icon></GridColumn>
    <GridColumn field="material_name" title="物料名称" min-width="120" show-icon></GridColumn>
    <GridColumn field="color" title="色号&颜色" min-width="120" show-icon></GridColumn>
    <GridColumn field="specification" title="规格" min-width="140" show-icon></GridColumn>
    <GridColumn field="idc2" title="识别码2（供应商/物料品类/物料名称/色号&颜色/规格）" min-width="340" show-icon>
      <template #header>
        <div>识别码2</div>
        <div>（供应商/物料品类/物料名称/色号&颜色/规格）</div>
      </template>
    </GridColumn>
    <GridColumn field="dup_statistics_by_idc2" title="识别码重复统计" min-width="140" show-icon></GridColumn>
    <GridColumn field="unit" title="单位" min-width="140" show-icon></GridColumn>
    <GridColumn field="inbound_by_idc2" title="按识别码统计入库数量-M/个" min-width="220" show-icon></GridColumn>
    <GridColumn field="total_inbound_amount" title="入库总金额" min-width="140" show-icon></GridColumn>
    <GridColumn field="weight_average_price" title="入库加权平均单价" min-width="160" show-icon></GridColumn>
    <GridColumn field="outbound_by_idc2" title="按识别码统计已出库数量-KG/M" min-width="180" show-icon></GridColumn>
    <GridColumn field="real_time_inventory" title="实时库存" min-width="120" show-icon sortable></GridColumn>
    <GridColumn field="inventory_idc" title="库存识别码" min-width="120" show-icon></GridColumn>
    <GridColumn field="inventory_amount" title="库存金额" min-width="120" show-icon></GridColumn>
    <GridColumn field="inventory_reason" title="库存原因" min-width="120" show-icon :editor="editor"></GridColumn>
    <GridColumn field="check" title="核对" min-width="120" show-icon :editor="editor"></GridColumn>
    <GridColumn field="review_result" title="复盘结果" min-width="120" show-icon :editor="editor"></GridColumn>
    <GridColumn field="remarks" title="备注" min-width="120" show-icon :editor="editor"></GridColumn>
    <GridColumn field="prompt" title="提示" min-width="120" show-icon></GridColumn>
    <GridColumn field="pre_safety_inventory" title="预安全库存量" min-width="180" show-icon :editor="editor"></GridColumn>
    <GridColumn field="remarks2" title="备注2" min-width="120" show-icon :editor="editor"></GridColumn>
  </Grid>
</template>

<script setup>
import { Grid, GridColumn, GridToolbar, Select, Option, Button, Modal } from '@opentiny/vue'
import { ref, onMounted, nextTick } from 'vue'
import {
  getWarehouseAuxiliaryInventory,
  updateWarehouseAuxiliaryInventory,
  getAuxiliarySupplied,
  getAuxiliaryMaterialCategory,
  getAuxiliaryMaterialName,
  getAuxiliaryIdc2,
  getAuxiliaryColor,
  getAuxiliarySpecification,
  getAuxiliaryWorkOrderNum,
  downloadAuxiliaryInventory
} from '@/request/api'
import { downLoadExcel } from 'untils'

const gridRef = ref()
const curParams = ref()
const supplied = ref('')
const suppliedOp = ref('')
const idc2 = ref('')
const idc2Op = ref([])
const material_category = ref('')
const materialCategoryOp = ref([])
const material_name = ref('')
const materialNameOp = ref([])
const colorOp = ref([])
const workOrderNumOp = ref([])
const color = ref('')
const specification = ref('')
const specificationOp = ref([])
const work_order_num = ref('')
const editor = ref({ component: 'input', autoselect: true })
const total_kg_in = ref()
const total_kg_out = ref()
const total_kg_inventory = ref()
const pagerConfig = ref({
  attrs: {
    currentPage: 1,
    pageSize: 20,
    pageSizes: [10, 20, 30, 50, 100],
    total: 0,
    align: 'left',
    layout: 'total, prev, pager, next, jumper, sizes'
  }
})
const handleSearch  = () => {
  gridRef.value.pagerConfig.currentPage = 1
  gridRef.value.handleFetch()
}
function footerMethod({ columns, data }) {
  return [
    columns.map((column, columnIndex) => {
      if (columnIndex === 0) {
        return '汇总'
      }
      if (column.property === 'inbound_by_idc2') {
        return total_kg_in.value
      }
      if (column.property === 'outbound_by_idc2') {
        return total_kg_out.value
      }
      if (column.property === 'real_time_inventory') {
        return total_kg_inventory.value
      }
      return null
    })
  ]
}
const getData = ({ page, sort }) => {
  const { field, order } = sort || {}
  return new Promise((resolve) => {
    const size = page.pageSize
    const currentPage = page.currentPage
    const params = {
      idc_2: encodeURIComponent(idc2.value),
      supplier: encodeURIComponent(supplied.value),
      category: encodeURIComponent(material_category.value),
      size,
      currentPage,
      name: encodeURIComponent(material_name.value),
      color: encodeURIComponent(color.value),
      work_order_num: encodeURIComponent(work_order_num.value),
      specification: encodeURIComponent(specification.value),
      sort: field,
      sort_seq: order || 'asc'
    }
    curParams.value = params
    getWarehouseAuxiliaryInventory(params).then(res => {
      total_kg_in.value = res.data.total_kg_in
      total_kg_out.value = res.data.total_kg_out
      total_kg_inventory.value = res.data.total_kg_inventory
      if (res?.data?.ret === 0) {
        resolve({
          result: res.data.result,
          page: { total: res.data.total }
        })
      } else {
        resolve({
          result: [],
          page: { total: 0 }
        })
      }
    })
  })
}
const exportFile = () => {
  const params = {
    ...curParams.value 
  }
  downloadAuxiliaryInventory(params).then(res => {
    downLoadExcel(res)
  })
}
const fetchData = {
  api: getData
}
const editClosed = ({ column, row }) => {
  const field  = column.property
  const title = column.title
  const hasChange = gridRef.value.hasRowChange(row, field)
  if (hasChange) {
    const params = {
      id: row.id
    }
    params.edit_field = field
    params.edit_value = row[field]
    updateWarehouseAuxiliaryInventory(params).then(res => {
      if (res?.data?.ret === 0) {
        Modal.message({ message: '编辑成功', status: 'success' })
        gridRef.value.handleFetch()
      } else {
        Modal.message({ message: res.data.msg, status: 'error' })
      }
    })
  }
}
const getInitData = () => {
  getAuxiliarySupplied().then(res => {
    if (res?.data?.ret === 0) {
      suppliedOp.value = res.data.result
    }
  })
  getAuxiliaryIdc2().then(res => {
    if (res?.data?.ret === 0) {
      idc2Op.value = res.data.result
    }
  })
  getAuxiliaryMaterialCategory().then(res => {
    if (res?.data?.ret === 0) {
      materialCategoryOp.value = res.data.result
    }
  })
  getAuxiliaryMaterialName().then(res => {
    if (res?.data?.ret === 0) {
      materialNameOp.value = res.data.result
    }
  })
  getAuxiliaryColor().then(res => {
    if (res?.data?.ret === 0) {
      colorOp.value = res.data.result
    }
  })
  getAuxiliarySpecification().then(res => {
    if (res?.data?.ret === 0) {
      specificationOp.value = res.data.result
    }
  })
  getAuxiliaryWorkOrderNum().then(res => {
    if (res?.data?.ret === 0) {
      workOrderNumOp.value = res.data.result
    }
  })
}
onMounted(() => {
  nextTick(() => {
    getInitData()
  })
})
</script>
<style lang="scss" scoped>
.tiny-select {
  width: inherit;
  margin-left: 10px;
}
:deep(.tiny-grid-toolbar .tiny-grid-custom__wrapper) {
  top: 35px;
}
</style>